<?php
	class PubmedApiImplDAO implements RepositoryDAO{
		/**
		 * Get Document Object by doi
		 *
		 * @param String $doi
		 */
		public function searchByDoi($doi){
			
			
				
			$request_url = str_replace('[DOI]', $doi, RepositoryConnectionProperty::$_url);
			RepositoryConnectionProperty::$_url = $request_url;
			
			
			//Connect to the Repository
			$conn = new RepositoryConnection();
			
			//The connection returns an XML object
			$xml=$conn->getConnection();
				
			//Create empty objects for Document, Metadata and File
			$document = new Document();
			$metadata = new Metadata();
			$file = new File();
			$keywords = array();
			$document->setMetadata($metadata);
			$document->setFile($file);
			$count = $xml->Count;
			if ($count == 1) $pmid = $xml->IdList->Id;
			if(isset($pmid)){
				
				$request_url_pubmed_pmid = "http://www.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=Pubmed&rettype=abstract&retmode=XML&id=[PMID]&tool=I,Librarian&email=i.librarian.software@gmail.com";
				RepositoryConnectionProperty::$_url = $request_url_pubmed_pmid;
			
				$document = $this->searchByUid($pmid);
			}
			return $document;
			
		}
		
		/**
		 * Get Document Object by uid
		 * @param String $uid
		 */
		public function searchByUid($uid){
			
			$request_url = str_replace('[PMID]', $uid, RepositoryConnectionProperty::$_url);
			RepositoryConnectionProperty::$_url = $request_url;
			
			//Connect to the Repository
			$conn = new RepositoryConnection();
				
			//The connection returns an XML object
			$xml=$conn->getConnection();
			
			//Create empty objects for Document, Metadata and File
			$document = new Document();
			$metadata = new Metadata();
			$file = new File();
			$keywords = array();
			
			
			$istitle = '';
			if(!empty($xml)) $istitle = $xml->PubmedArticle->MedlineCitation->Article->ArticleTitle;
			
			if(!empty($istitle)) {
			
				if (!isset($doi)) {
			
					foreach ($xml->PubmedArticle->PubmedData->ArticleIdList->ArticleId as $articleid) {
			
						preg_match ('/10\.\d{4}\/\S+/i', $articleid, $doi);
			
						if (count($doi) > 0) {
							$doi = current($doi);
							break;
						}
					}
				}
				
				if (!empty($doi)) $metadata->setDoi($doi);
				if (!empty($uid)){
					$document->setUid("PMID:".(string)$uid);
					$metadata->setUrl("http://www.pubmed.org/$uid");	
				}
				}
				if (!empty($xml->PubmedArticle->MedlineCitation->Article->PublicationTypeList->PublicationType[0]))
					$metadata->setReferenceType((string)strtolower($xml->PubmedArticle->MedlineCitation->Article->PublicationTypeList->PublicationType[0]));
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->ArticleTitle)){
					$metadata->setTitle((string)$xml->PubmedArticle->MedlineCitation->Article->ArticleTitle);
					$metadata->setTitleAscii(utf8_deaccent((string)$xml->PubmedArticle->MedlineCitation->Article->ArticleTitle));
				}
				
				$abstract_array = array();
				
				$xml_abstract = $xml->PubmedArticle->MedlineCitation->Article->Abstract->AbstractText;
				
				if(!empty($xml_abstract)) {
					foreach ($xml_abstract as $mini_ab) {
						foreach($mini_ab->attributes() as $a => $b) {
							if ($a == 'Label') $mini_ab = $b.": ".$mini_ab;
						}
						$abstract_array[] = "$mini_ab";
					}
					$metadata->setAbstract(implode(' ', $abstract_array));
					$metadata->setAbstractAscii(utf8_deaccent(implode(' ', $abstract_array)));
				}
				
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->Journal->Title))
					$metadata->setSecondaryTitle((string)$xml->PubmedArticle->MedlineCitation->Article->Journal->Title);
				
				$day			= (string) $xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->PubDate->Day;
				$month			= (string) $xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->PubDate->Month;
				$year			= (string) $xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->PubDate->Year;
				
				if (empty($year)) {
					$year = (string) $xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->PubDate->MedlineDate;
					preg_match ('/\d{4}/', $year, $year_match);
					$year = $year_match[0];
				}
				
				$metadata->setYear('');
				if (!empty($year)) {
					if(empty($day)) $day = '01';
					if(empty($month)) $month = '01';
					$metadata->setYear(date('Y-m-d', strtotime($day.'-'.$month.'-'.$year)));
				}
				
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->Volume))
					$metadata->setVolume((string)$xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->Volume);
				
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->Issue))
				 	$metadata->setIssue((string)$xml->PubmedArticle->MedlineCitation->Article->Journal->JournalIssue->Issue);
				
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->Pagination->MedlinePgn))
					$metadata->setPages((string)$xml->PubmedArticle->MedlineCitation->Article->Pagination->MedlinePgn);
				
				if(!empty($xml->PubmedArticle->MedlineCitation->MedlineJournalInfo->MedlineTA))
					$metadata->setJournal((string)$xml->PubmedArticle->MedlineCitation->MedlineJournalInfo->MedlineTA);
				
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->Affiliation))
					$metadata->setAffiliation((string)$xml->PubmedArticle->MedlineCitation->Article->Affiliation);
				
				if(!empty($xml->PubmedArticle->MedlineCitation->Article->AuthorList->Author))
					$authors = $xml->PubmedArticle->MedlineCitation->Article->AuthorList->Author;
				
				if (!empty($authors)) {
					foreach ($authors as $author) {
						$name_array[] = $author->LastName.' '.$author->Initials;
					}
				}
				
				$mesh = $xml->PubmedArticle->MedlineCitation->MeshHeadingList->MeshHeading;
				
				$i=0;
				if (!empty($mesh)) {
					foreach ($mesh as $meshheading) {
						$mesh_array[] = $meshheading->DescriptorName;
						$keyword = new Keyword();
						$keyword->setKeyword((string)$meshheading->DescriptorName);
						$keyword->setSelected(true);
						$keywords[$i]=$keyword;
						$i++;
					}
				}
				
				if (isset($name_array)){
					$metadata->setAuthors(join (", ", $name_array));
					$metadata->setAutorsAscii(utf8_deaccent(join (", ", $name_array)));
				}
				if (isset($mesh_array)) $metadata->setKeywords($keywords);
				
				$document->setMetadata($metadata);
				$document->setFile($file);
					
				//Return the Document Object
				return $document;
			
		}
		
		public function findDoiByISSN($issn, $title){}
		
		public function searchByTitle($title){}
	}